/**
 * Created by lee_mxue on 17/5/8.
 */
import React from "react";
import ReactDOM from "react-dom";
import tools from "../../lib/tools";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare"
import AJAX from "../../lib/ajax"
require('../../lib/rem');
require('./ChooseCabinetType.less');
require('../../styles/common.less');
require('../../styles/resetWeui.less');
require('../../styles/lux.less')
const Dialog = require('../MyPackage/components/Dialog')
let PictureSlick = require('../../components/PictureSlick')
const Toast = require('../MyPackage/components/Toast')
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isReady: false,     //是否可以加载页面
            selectedCabinetData: {
                "type": 0,  //int 格口类型,
                "type_desc": "",    //str 格口类型描述,
                "tariff_id": 0,     //int 资费ID,
                "price": "",    //int 价格,
                "idle_count": 0,    //int 可用数量,
                "length": 0,    //int 长(单位: 毫米),
                "width": 0,     //int 宽(单位: 毫米),
                "height": 0,    //int 高(单位: 毫米),
                "img_list": []
            },    //已选格口信息
            pictureIsOpen: false,   //图片预览开关
            img_data: [
                {src: "http://i1.piimg.com/1949/5b41d6c69854148e.png"},
                {src: "http://i1.piimg.com/1949/5b41d6c69854148e.png"},
                {src: "http://i1.piimg.com/1949/5b41d6c69854148e.png"},
                {src: "http://i1.piimg.com/1949/5b41d6c69854148e.png"},
            ],   //图片预览数据
            cabinet_data: {
                "id": 0,
                "name": '',     //str 名称,
                "code": '',     //str 柜体编号,
                "addr": '',     //str 详细地址,
                "cell_summary": [],     // # 格口信息概要
            },      //柜体详情
        };
        this.switchPicture = this.switchPicture.bind(this);//图片预览
        this.confirmOpen = this.confirmOpen.bind(this);//确认开箱
        this.handleChooseCabient = this.handleChooseCabient.bind(this);//选择格口

    }

    componentWillMount() {
        //获取柜体编码
        var cabinet_code = tools.getParams().cabinet_code;
        //获取订单id
        var order_id = tools.getParams().order_id;
        //is_reselect[选填]: 是否重选格口（是:1, 否:0, 默认0）
        var is_reselect = tools.getParams().is_reselect || 0;
        var _this = this;
        addErrorListener()()
        //隐藏分享功能
        weixinShare.hideAll();

        //获取柜体详情
        // alert(cabinet_id)
        AJAX.request('order_cabinet_info', {
            order_id: order_id, //订单ID
            cabinet_code: cabinet_code, // 柜体编号
            is_reselect: is_reselect  // is_reselect[选填]: 是否重选格口（是:1, 否:0, 默认0）
        }, data => {
            if(data.code == 0){
                _this.setState({
                    cabinet_data: data.body,
                    isReady: true,     //是否可以加载页面
                })
                //如果有格口信息，证明已投递但未确认关箱，需弹窗提示
                if(data.body.cell_id){
                    var closeParams = {
                        order_id: order_id, //订单id
                        cabinet_code: cabinet_code, //柜体编号
                        cell_id: data.body.cell_id,    //格口id
                    }
                    Dialog.info({
                        title: "",
                        content: "已有快递放入格口，请确认关箱。",
                        okText: "确认",
                        onOK: ()=> {
                            AJAX.request("confirm_delivery", closeParams, data => {
                                if(data.code == 0){
                                    window.location.href = './CabinetOpening?cabinet_code=' + cabinet_code + '&order_id=' + order_id +"&fee="+data.body.fee
                                }
                            })
                        }
                    })
                }
                //    清楚已选开箱参数
                window.localStorage.removeItem("open_cabinetInfo_x");
            }
        })

    }


    componentDidMount() {
        AJAX.appendBaiduAnalysis()
    }

    //toast弹窗
    warn(content) {
        Toast.warn({
            content: content
        })
    }

    success() {
        Toast.success({
            content: "成功"
        })
    }

    error() {
        Toast.error({
            content: "失败"
        })
    }

    loading() {
        Toast.loading({
            content: "数据加载中"
        })
    }

    //选择格口
    handleChooseCabient(item) {
        this.setState({
            selectedCabinetData: item
        })
    }

    //图片预览
    switchPicture(img_list) {
        var _this = this;
        if(img_list){
            var img_data = [];  //构造数据源
            img_list.map(item => {
                var data_item = {
                    src: item
                }
                img_data.push(data_item)
            });
            this.setState({
                img_data: img_data,
            })
        }
        this.setState({
            pictureIsOpen: !_this.state.pictureIsOpen,
        })
    }

    //确认开箱
    confirmOpen() {

//获取柜体编码
        var cabinet_code = tools.getParams().cabinet_code;
//获取订单id
        var order_id = tools.getParams().order_id;
        var cabinetInfo = {
            order_id: order_id,     //[必选]: 订单ID
            cabinet_code: cabinet_code,     //[必选]: 柜体编号
            cell_id: this.state.selectedCabinetData.cell_id,  //格口Id
            cell_type: this.state.selectedCabinetData.type,  //格口类型
            tariff_id: this.state.selectedCabinetData.tariff_id, //[必选]: 格口对应的资费ID
            price: this.state.selectedCabinetData.price, // 格口对应的资费
        }
        window.localStorage.setItem("open_cabinetInfo_x", JSON.stringify(cabinetInfo))
        window.location.href = './CabinetOpening?cabinet_code=' + cabinet_code + '&order_id=' + order_id +"&url=open"
    }

    render() {

//获取柜体编码
        var cabinet_code = tools.getParams().cabinet_code;
//获取订单id
        var order_id = tools.getParams().order_id;

        const selectedCabinetData = this.state.selectedCabinetData || {}
        let text = ""
        if(selectedCabinetData.limit_weight > 0) {
            let weight  = selectedCabinetData.limit_weight/1000
            if(weight%1 !==0){
                weight = weight.toFixed(1)
            }
            text = `此格口限重${weight}公斤，超重可能会导致快件被退回。`
        }

        const have_list = this.state.cabinet_data.cell_summary.length > 0 

        return (
            this.state.isReady &&
            <div className="main">
                <div className=" top_active">
                    <h3>温馨提示：</h3>
                    <p>1、格口的最高限重（含包装）分别为：小／超小格口为1kg，中格口为3kg，大格口为5kg；</p>
                    <p>2、需要寄出的物品请勿封口，方便验视。</p>
                    <p>3、为防止您的快递因为不符合收寄标准被退回而造成延误，请您务必查看 <a
                        href={"./PackagePrinciple?cabinet_code=" + cabinet_code + "&order_id=" + order_id}>《收寄原则》</a>
                    </p>
                    <p>4、最终收取费用以实际发生为准，多余钱款将退回账户。</p>
                </div>
                {
                    have_list &&
                    <div className="center_content">
                        <div className="clear">
                            {this.state.cabinet_data.cell_summary.map(item => {
                                return (
                                    <div className="floatL">
                                        <div className="imgBox" onClick={this.switchPicture.bind(this, item.img_list)}>
                                            <img src={item.img_list[0]} alt=""/>
                                            <p>{item.width / 10}cm*{item.height / 10}cm*{item.length / 10}cm</p>
                                        </div>

                                        <div className="radioBox">
                                            <i className={this.state.selectedCabinetData.type === item.type ? "textYellow iconfont icon-icondian fontSize14px" : "iconfont icon-iconfontwancheng fontSize14px"}
                                            onClick={this.handleChooseCabient.bind(this, item)}/>
                                            <span>{item.type_desc}(剩{item.idle_count})</span>
                                        </div>
                                    </div>
                                )
                            })}
                        </div>
                    </div>
                }
                <div className="lux-text-warn">
                    <span className="textRed">{text}</span>
                </div>
                {  !have_list &&
                    <div>
                        <div className="lux-text-warn" >
                            <span className="textRed">当前柜体已满，暂无可用格口</span>
                        </div>
                    </div>
                }
                {
                    have_list &&
                    <div className="bottom_submit">
                        <a className="weui-btn weui-btn_primary yellow" onClick={this.confirmOpen} href="javascript:;"
                        id="showTooltips">打开格口({(this.state.selectedCabinetData.price / 100).toFixed(2)}元)</a>
                    </div>
                }
                {/*图片预览展示*/}
                {this.state.pictureIsOpen &&
                <PictureSlick switchPicture={this.switchPicture} img_data={this.state.img_data}/>}
            </div>
        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}